package br.edu.univas.si.lab3.bankmanager.view;

import java.awt.Font;
import java.text.ParseException;

import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;

import br.edu.univas.si.lab3.bankmanager.model.ClienteFisicoTO;
import br.edu.univas.si.lab3.bankmanager.model.ClienteJuridicoTO;
import br.edu.univas.si.lab3.bankmanager.model.ClienteTO;

public class PanelChave extends JPanel{
	private static final long serialVersionUID = 1L;
	
	private JLabel chaveDeBusca;
	private JFormattedTextField cpfField;
	private JFormattedTextField cnpjField;
	private ClienteTO cliente;

	public PanelChave(ClienteTO cliente) {
		this.cliente = cliente;
		initialize();
	}
	
	private void initialize(){
		add(getChaveLabel());
		
		if(this.cliente instanceof ClienteFisicoTO){
			add(getCpfField());
		}else if(this.cliente instanceof ClienteJuridicoTO){
			add(getCnpjField());
		}
	}
	
	private JLabel getChaveLabel(){
		if(chaveDeBusca == null){
			chaveDeBusca = new JLabel("Chave de busca");
			chaveDeBusca.setFont(new Font("Times New Roman", Font.BOLD+Font.ITALIC, 16));
		}
		return chaveDeBusca;
	}
	
	private JFormattedTextField getCpfField(){
		if (cpfField == null){
			cpfField = new JFormattedTextField(getMask("  ###.###.###-##  "));
			cpfField.setToolTipText("Informe o cpf");
		}
		return cpfField;
	}
	
	private JFormattedTextField getCnpjField(){
		if (cnpjField == null){
			cnpjField = new JFormattedTextField(getMask("  ##.###.###/####-##  "));
			cnpjField.setToolTipText("Informe o cnpj");
		}
		return cnpjField;
	}
	
	private MaskFormatter getMask(String maskString) {
		MaskFormatter mask = new MaskFormatter();
		
		try {
			mask.setMask(maskString);
			mask.setPlaceholderCharacter('_');
		} 
		catch (ParseException e) {
			System.out.println("Erro: " + maskString);
		}
		
		return mask;
	}

	public String getChave() {
		String chave = "";
		if(this.cliente instanceof ClienteFisicoTO)
			chave = removeSpace(cpfField.getText());
		else if(this.cliente instanceof ClienteJuridicoTO)
			chave = removeSpace(cnpjField.getText());
		return chave;
	}
	
	private String removeSpace(String string){
	    String stringFormatada = "";
	        
	    for (int i = 0; i < string.length(); i++ ) {    
	        if ( string.charAt(i) != ' '){
	        	stringFormatada += string.charAt(i);
	        }
	    }    
	    return stringFormatada;
	}
}
